﻿@model Apps.Models.WMS.WMS_ReturnInspectionModel
@using Apps.Web.Core;
@using Apps.Common;
@using Apps.Models.WMS;
@using Apps.Web;
@using Apps.Locale;
@using Apps.Models.Sys;
@{
    ViewBag.Title = "创建退货送检单";
    Layout = "~/Views/Shared/_Index_LayoutEdit.cshtml";
    List<permModel> perm = null;
}

<script type="text/javascript">
    $(function ()
    {
        $("#btnSave").click(function ()
        {
            if (!$("form").valid()) {
                $.messageBox5s('提示', $("#ErrMesList").html());
                return;
            }
            if ($("form").valid())
            {
                endEditing_mList();
                var $dg = $('#mList');
                var rows = $dg.datagrid('getRows');  //获取所有的行

                //对最后一行进行判断，如果PartId为空则删除最后一行
                if (!rows[rows.length - 1]['PartId'])
                {
                    rows.pop();
                }
                //判断是否存在PartId为空的行
                for (var i = 0; i < rows.length; i++)
                {
                    if (!rows[i]['PartId'])
                    {
                        alert("存在无效的物料，请确认！");
                        return;
                    }
                }

                //将所选中的行转换成json字符串，并保存到inserted隐藏输入框中。
                $("#inserted").val(JSON.stringify(rows));

                if (rows.length) {
                    showLoading();
                    $.ajax({
                        url: "@Url.Action("Create")",
                        type: "Post",
                        data: $("form").serialize(),
                        dataType: "json",
                        success: function (data) {
                            if (data.type == 1) {
                                hideLoading();
                                //window.parent.frameReturnByMes(data.message);
                                //window.parent.frameReturnByReload(true);
                                //window.parent.frameReturnByClose()

                                //打开报表打印的窗口
                                self.location = '@Url.Action("ShowBill", "ReportManager", new { area = "Report" })?reportCode=ReturnInspect&billNum=' + data.value;
                            } else
                            {
                                window.parent.frameReturnByMes(data.message);
                                hideLoading();

                            }
                        }
                    });
                } else {
                    $.messageBox5s('提示', "没有数据需要保存！");
                }
            }
        });
        $("#btnReturn").click(function () {
            window.parent.frameReturnByClose();
        });

        $(window).resize(function () {
            $('#List').datagrid('resize', {

            }).datagrid('resize', {
                width: SetGridWidthSub(30),
                height: SetGridHeightSub(50)
            });
        });

    });
    $(function ()
    {
        $('#mList').datagrid({
            url: '@Url.Action("GetReturnInspectBillList")',
            methord: 'post',
            width: SetGridWidthSub(10),
            height: SetGridHeightSub(202),
            fitColumns: true,
            idField: 'Id',
            pagination: false,
            striped: true, //奇偶行是否区分
            singleSelect: true,//单选模式
            selectOnCheck: false,
            checkOnSelect: false,
            onClickCell: onClickCell_mList,
            onEndEdit: onEndEdit_mList,
            onBeginEdit: onBeginEdit_mList,
            remotesort: false,
            showFooter: false,
            onLoadSuccess: function (data)
            {
                append();
            },
            columns: [[
                { field: 'Id', title: 'Id', width: 80, hidden: true },
                {
                    field: 'oper', title: '操作', width: 50, formatter: function (value)
                    {
                        if (value == null)
                            return "<a class='fa fa-plus color-green' href='javascript:append()'><a>&nbsp;&nbsp;&nbsp;<a class='fa fa-minus color-red' href='javascript:removeit()'><a>";
                        else
                            return value;
                    }
                },

                {
                    field: 'PartCustomerCode', title: '客户图号', width: 100,
                    editor: { type: 'textbox', options: { required: true } }
                },
                { field: 'PartCode', title: '物料编码', width: 80, hidden: true },
                {
                    field: 'PartId', title: '物料', width: 100,
                    formatter: function (value, row)
                    {
                        return row.PartCode;
                    },
                    editor:
                    {
                        type: 'combogrid',
                        options:
                        {
                            panelWidth: 600,
                            panelHeight: 150,
                            idField: 'Id',
                            textField: 'FullPartName',
                            url: '@Url.Action("GetPartListByCustomerCode", "Part")',
                            method: 'post',
                            editable: false,
                            columns: [[
                                { field: 'Id', title: '物料ID', width: 50, hidden: true },
                                { field: 'FullPartName', title:'物料全称',width:200 },
                                { field: 'PartType', title: '物料类型', width: 80 },
                                { field: 'BelongSupplier', title: '所属供应商', width: 160 },
                                { field: 'BelongCustomer', title: '所属客户', width: 160 },
                            ]],
                            fitColumns: true,
                            onBeforeLoad: function (param)
                            {
                                var customerCode = getPartCustomerCode();
                                if (customerCode)
                                {
                                    param.customerCode = customerCode;
                                    param.type = 'datagrid';
                                }
                                else
                                {
                                    return false;
                                }
                            },
                            onSelect: function (rowIndex, rowData)
                            {
                                //赋值给物料类别
                                var row = $('#mList').datagrid('getSelected');
                                var rowIndex_mlist = $('#mList').datagrid('getRowIndex', row);//获取行号
                                var td = $('.datagrid-body td[field="PartType"]')[rowIndex_mlist];
                                var div = $(td).find('div')[0];
                                $(div).text(rowData.PartType);
                                row.PartType = rowData.PartType;

                                //根据所属客户，确定客户下拉列表的值
                                var row = $('#mList').datagrid('getSelected');
                                var rowIndex_mlist = $('#mList').datagrid('getRowIndex', row);//获取行号
                                var lotTarget_c = $('#mList').datagrid('getEditor', { 'index': rowIndex_mlist, 'field': 'CustomerId' }).target;
                                $(lotTarget_c).combogrid('clear');
                                var td_c = $('.datagrid-body td[field="CustomerShortName"]')[rowIndex_mlist];
                                var div_c = $(td_c).find('div')[0];
                                $(div_c).text("");
                                var lotTarget_Grid_c = $(lotTarget_c).combogrid('grid');
                                lotTarget_Grid_c.datagrid('load', { codes: rowData.BelongCustomer });

                                //根据所属供应商，确定供应商下拉列表的值
                                //var lotTarget_s = $('#mList').datagrid('getEditor', { 'index': rowIndex_mlist, 'field': 'SupplierId' }).target;
                                //$(lotTarget_s).combogrid('clear');
                                //var td_s = $('.datagrid-body td[field="SupplierShortName"]')[rowIndex_mlist];
                                //var div_s = $(td_s).find('div')[0];
                                //$(div_s).text("");
                                //var lotTarget_Grid_s = $(lotTarget_s).combogrid('grid');
                                //lotTarget_Grid_s.datagrid('load', { codes: rowData.BelongSupplier });
                            },
                        }
                    }
                },
                { field: 'PartType', title: '物料类型', width: 80 },

                { field: 'CustomerCode', title: '客户ID', width: 80, hidden: true },
                {
                    field: 'CustomerId', title: '客户', width: 100,
                    formatter: function (value, row)
                    {
                        return row.CustomerCode;
                    },
                    editor:
                    {
                        type: 'combogrid',
                        options:
                        {
                            panelWidth: 300,
                            panelHeight: 150,
                            idField: 'Id',
                            textField: 'CustomerCode',
                            url: '@Url.Action("GetCustomerByBelong", "Customer")',
                            method: 'post',
                            editable: false,
                            columns: [[
                                { field: 'Id', title: '客户ID', width: 50, hidden: true },
                                { field: 'CustomerCode', title:'客户编码',width:80 },
                                { field: 'CustomerShortName', title: '客户简称', width: 80 },
                                { field: 'CustomerName', title: '客户名称', width: 140 },
                            ]],
                            fitColumns: true,
                            onSelect: function (rowIndex, rowData)
                            {
                                //赋值给客户简称
                                var row = $('#mList').datagrid('getSelected');
                                var rowIndex_mlist = $('#mList').datagrid('getRowIndex', row);//获取行号
                                var td = $('.datagrid-body td[field="CustomerShortName"]')[rowIndex_mlist];
                                var div = $(td).find('div')[0];
                                $(div).text(rowData.CustomerShortName);
                                row.CustomerShortName = rowData.CustomerShortName;
                            },
                        }
                    }
                },
                { field: 'CustomerShortName', title: '客户简称', width: 100 },

                {
                    field: 'Qty', title: '退货数量', width: 80,
                    editor: { type: 'numberbox', options: { required: true, min: 0 } }, align: 'right'
                },
                { field: 'PCS', title: '箱数', width: 80, editor: { type: 'numberbox' } },
                { field: 'Volume', title: '体积', width: 80, editor: { type: 'numberbox' } },
                { field: 'Remark', title: '退货说明', width: 80, editor: { type: 'textbox' }},

            ]]
        });
    });

    //#region 手动加载DataGrid的事件
    //编辑的行
    var editIndex_mList = undefined;
    function endEditing_mList()
    {
        if (editIndex_mList == undefined) { return true }
        $('#mList').datagrid('endEdit', editIndex_mList);

        editIndex_mList = undefined;
        return true;
    }

    //添加空行—手动加载
    function append()
    {
        var index = $('#mList').datagrid('getRowIndex', $('#mList').datagrid('getSelected'));
        if (index == -1)
            index = 0;
        $("#mList").datagrid("insertRow", {
            index: index + 1,
            row: {
                oper: "<a class='fa fa-plus color-green' href='javascript:append()'><a>&nbsp;&nbsp;&nbsp;<a class='fa fa-minus color-red' href='javascript:removeit()'><a>",
            }
        });
    }

    //删除一行—手动加载
    function removeit()
    {
        if (editIndex_mList == undefined) { return }
        $('#mList').datagrid('selectRow', editIndex_mList);

        $('#mList').datagrid('cancelEdit', editIndex_mList)
            .datagrid('deleteRow', editIndex_mList);
        editIndex_mList = undefined;
    }

    function onEndEdit_mList(index, row)
    {
        var ed = $(this).datagrid('getEditor', {
            index: index,
            field: 'PartId'
        });
        row.PartCode = $(ed.target).combobox('getText');
    }

    //进入编辑前设置
    function onBeginEdit_mList(index, row)
    {
    }

    function onClickCell_mList(index, field)
    {
        if (editIndex_mList != index)
        {
            if (endEditing_mList())
            {
                $('#mList').datagrid('selectRow', index)
                    .datagrid('beginEdit', index);

                //给numberbox增加keyup事件，以便自动计算合格数量和不合格数量
                var eds = $('#mList').datagrid('getEditors', index);
                for (var i = 0; i < eds.length; i++)
                {
                    var ed = eds[i];
                    //给字段PartCustomerCode增加setKeyUpValue事件
                    if (ed.field == 'PartCustomerCode')
                    {
                        var target = $(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target);
                        target.bind("keyup", function (e)
                        {
                            return setKeyUpValueForPartCustomerCode(e, $(this), $('#mList'));
                        });
                    }

                    if (ed.field == 'PartId')
                    {
                        var target = $(ed.target).combobox('textbox');
                        target.bind("focus", function ()
                        {
                            return setFocusForPartId(index);
                        });
                        target.bind("keyup", function (e)
                        {
                            return setKeyUpValueForPartId(e, index);
                        });
                    }

                    //给字段CustomerId增加setKeyUpValue事件
                    if (ed.field == 'CustomerId')
                    {
                        var target = $(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target);
                        target.bind("focus", function ()
                        {
                            return setFocusForCustomerId(index);
                        });
                        target.bind("keyup", function (e)
                        {
                            return setKeyUpValueForCustomerId(e, $(this), $('#mList'));
                        });
                    }

                    //给字段SupplierId增加setKeyUpValue事件
                    //if (ed.field == 'SupplierId')
                    //{
                    //    var target = $(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target);
                    //    target.bind("focus", function ()
                    //    {
                    //        return setFocusForSupplierId(index);
                    //    });
                    //    target.bind("keyup", function (e)
                    //    {
                    //        return setKeyUpValueForSupplierId(e, $(this), $('#mList'));
                    //    });
                    //}

                    //给字段Qty增加setKeyUpValue事件
                    if (ed.field == 'Qty')
                    {
                        var target = $(ed.target).data('textbox') ? $(ed.target).numberbox('textbox') : $(ed.target);
                        target.bind("focus", function ()
                        {
                            return setFocusForQty($(ed.target));
                        });
                        target.bind("keyup", function (e)
                        {
                            return setKeyUpValueForQty(e, index);
                        });
                    }

                    //给字段PCS增加setKeyUpValue事件
                    if (ed.field == 'PCS')
                    {
                        var target = $(ed.target).data('textbox') ? $(ed.target).numberbox('textbox') : $(ed.target);
                        target.bind("focus", function ()
                        {
                            return setFocusForPCS($(ed.target));
                        });
                        target.bind("keyup", function (e)
                        {
                            return setKeyUpValueForPCS(e, index);
                        });
                    }

                    //给字段Volume增加setKeyUpValue事件
                    if (ed.field == 'Volume')
                    {
                        var target = $(ed.target).data('textbox') ? $(ed.target).numberbox('textbox') : $(ed.target);
                        target.bind("focus", function ()
                        {
                            return setFocusForVolume($(ed.target));
                        });
                        target.bind("keyup", function (e)
                        {
                            return setKeyUpValueForVolume(e, index);
                        });
                    }

                    //给字段Remark增加setKeyUpValue事件
                    if (ed.field == 'Remark')
                    {
                        var target = $(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target);
                        target.bind("keyup", function (e)
                        {
                            return setKeyUpValueForRemark(e, index);
                        });
                    }
                }

                var ed = $('#mList').datagrid('getEditor', { index: index, field: field });
                if (ed)
                {
                    ($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus();
                    ($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).select();
                }
                editIndex_mList = index;
            } else
            {
                setTimeout(function ()
                {
                    $('#mList').datagrid('selectRow', editIndex);
                }, 0);
            }
        }
    }

    function ChangeFocus(index, field)
    {
        var ed = $('#mList').datagrid('getEditor', { index: index, field: field });
        if (ed)
        {
            ($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus();
            ($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).select();
        }
    }

    //获取输入的物料客户编码
    function getPartCustomerCode()
    {
        if ($('.datagrid-body').length > 0)
        {
            var row = $('#mList').datagrid('getSelected');
            var rowIndex = $('#mList').datagrid('getRowIndex', row);//获取行号
            var thisTarget = $('#mList').datagrid('getEditor', { 'index': rowIndex, 'field': 'PartCustomerCode' }).target;
            var thisTarget_Input = $(thisTarget).data('textbox') ? $(thisTarget).textbox('textbox') : $(thisTarget);
            if (thisTarget_Input.val())
                return thisTarget_Input.val();
            if (row.PartCustomerCode)
                return row.PartCustomerCode
        }
        else
        {
            return 0;
        }
    }

    function setKeyUpValueForPartCustomerCode(e, sender, datagrid)
    {
        var code = e.keyCode || e.which;
        if (code == 13)
        {
            var row = datagrid.datagrid('getSelected');
            var rowIndex = datagrid.datagrid('getRowIndex', row);//获取行号
            var thisTarget = datagrid.datagrid('getEditor', { 'index': rowIndex, 'field': 'PartCustomerCode' }).target;
            var thisTarget_Input = $(thisTarget).data('textbox') ? $(thisTarget).textbox('textbox') : $(thisTarget);

            var thisTarget_Part = $('#mList').datagrid('getEditor', { 'index': rowIndex, 'field': 'PartId' }).target;
            thisTarget_Part.combogrid('clear');
            thisTarget_Part.combogrid('grid').datagrid('reload');

            var thisTarget_Customer = $('#mList').datagrid('getEditor', { 'index': rowIndex, 'field': 'CustomerId' }).target;
            thisTarget_Customer.textbox('clear');
            //var thisTarget_Supplier = $('#mList').datagrid('getEditor', { 'index': rowIndex, 'field': 'SupplierId' }).target;
            //thisTarget_Supplier.textbox('clear');
            var thisTarget_Qty = $('#mList').datagrid('getEditor', { 'index': rowIndex, 'field': 'Qty' }).target;
            thisTarget_Qty.textbox('clear');
            var thisTarget_PCS = $('#mList').datagrid('getEditor', { 'index': rowIndex, 'field': 'PCS' }).target;
            thisTarget_PCS.textbox('clear');
            var thisTarget_Volume = $('#mList').datagrid('getEditor', { 'index': rowIndex, 'field': 'Volume' }).target;
            thisTarget_Volume.textbox('clear');
            var thisTarget_Remark = $('#mList').datagrid('getEditor', { 'index': rowIndex, 'field': 'Remark' }).target;
            thisTarget_Remark.textbox('clear');

            ChangeFocus(rowIndex, "PartId");
        }
    }

    function setFocusForPartId(rowIndex)
    {
        var thisTarget = $('#mList').datagrid('getEditor', { 'index': rowIndex, 'field': 'PartId' }).target;
        thisTarget.combobox('showPanel');
    }
    function setKeyUpValueForPartId(e, rowIndex)
    {
        var code = e.keyCode || e.which;
        if (code == 13)
        {
            ChangeFocus(rowIndex, "CustomerId");
        }
    }

    function setFocusForCustomerId(rowIndex)
    {
        var thisTarget = $('#mList').datagrid('getEditor', { 'index': rowIndex, 'field': 'CustomerId' }).target;
        thisTarget.combobox('showPanel');
    }
    function setKeyUpValueForCustomerId(e, sender, datagrid)
    {
        var code = e.keyCode || e.which;
        if (code == 13)
        {
            var row = datagrid.datagrid('getSelected');
            var rowIndex = datagrid.datagrid('getRowIndex', row);//获取行号
            ChangeFocus(rowIndex, "Qty");
        }
    }

    //function setFocusForSupplierId(rowIndex)
    //{
    //    var thisTarget = $('#mList').datagrid('getEditor', { 'index': rowIndex, 'field': 'SupplierId' }).target;
    //    thisTarget.combobox('showPanel');
    //}
    //function setKeyUpValueForSupplierId(e, sender, datagrid)
    //{
    //    var code = e.keyCode || e.which;
    //    if (code == 13)
    //    {
    //        var row = datagrid.datagrid('getSelected');
    //        var rowIndex = datagrid.datagrid('getRowIndex', row);//获取行号
    //        var thisTarget = datagrid.datagrid('getEditor', { 'index': rowIndex, 'field': 'SupplierId' }).target;
    //        var supplierId = $(thisTarget).combo('getValue');

    //        if ((row.PartType == "外购件") && !(supplierId))
    //            alert("外购件必须选择供应商！");
    //        else
    //            ChangeFocus(rowIndex, "Qty");
    //    }
    //}

    function setFocusForQty(sender)
    {
        sender.select();
    }
    function setKeyUpValueForQty(e, rowIndex)
    {
        var code = e.keyCode || e.which;
        if (code == 13)
        {
            ChangeFocus(rowIndex, "PCS");
        }
    }

    function setFocusForPCS(sender)
    {
        sender.select();
    }
    function setKeyUpValueForPCS(e, rowIndex)
    {
        var code = e.keyCode || e.which;
        if (code == 13)
        {
            ChangeFocus(rowIndex, "Volume");
        }
    }

    function setFocusForVolume(sender)
    {
        sender.select();
    }
    function setKeyUpValueForVolume(e, rowIndex)
    {
        var code = e.keyCode || e.which;
        if (code == 13)
        {
            ChangeFocus(rowIndex, "Remark");
        }
    }

    function setKeyUpValueForRemark(e, rowIndex)
    {
        var code = e.keyCode || e.which;
        if (code == 13)
        {
            var addNewLine = false;
            var rows = $('#mList').datagrid('getRows');
            if (rowIndex == rows.length - 1)
            {
                append();
                addNewLine = true;
            }
            endEditing_mList();

            if (addNewLine)
                onClickCell_mList(rowIndex + 1, "PartCustomerCode");
        }
    }
    //#endregion

    //关闭模式窗口
    function frameReturnByClose() {
        $("#modalwindow").window('close');
    }


    function reject() {
        $('#List').datagrid('rejectChanges');
        editIndex = undefined;
    }
    function getChanges() {
        var rows = $('#List').datagrid('getChanges');
        alert(rows.length + ' rows are changed!');
    }

    function contains(arr, obj) {
        var i = arr.length;
        while (i--) {
            if (arr[i] === obj) {
                return true;
            }
        }
        return false;
    }

    //ifram 返回
    function frameReturnByClose() {
        $("#modalwindow").window('close');
    }

    function frameReturnByMes(mes) {
        $.messageBox5s('提示', mes);
    }

    //清空控件的数据（暂时没用）。
    function clear()
    {
        $('#PONo').val("");
        $('#List').datagrid("Load");

    }
</script>

<div id="modalwindow" class="easyui-window" style="width:800px; height:400px;" data-options="modal:true,closed:true,minimizable:false,shadow:false"></div>
<div class="mvctool bgb">
    @Html.ToolButton("btnSave", "fa fa-save", Resource.Save, ref perm, "Save", true)
    @Html.ToolButton("btnReturn", "fa fa-reply", Resource.Reply, false)
</div>
@using (Html.BeginForm())
{
    <div id="ErrMesList">
        <div id="ErrMesListContent">
            @Html.ValidationSummary(false)
        </div>
    </div>
    @*@Html.HiddenFor(model => model.Id)*@
    <input id="inserted" type="hidden" name="inserted" value="" />
}
<table id="mList"></table>

